package cn.js.sangu.unitStore.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Slf4j
@EnableAsync
@Configuration
public class AsyncConfig {

    /**
     * 任务执行者：自定义线程池
     * @return
     */
    @Bean("taskExecutor")
    public Executor taskExecutor(){
        //处理器可用的Java虚拟机核心数
        int i = Runtime.getRuntime().availableProcessors();
        log.warn("====处理器最大可用线程数：【{}】 ====",i);
        //创建线程池任务执行者
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //线程池大小
        executor.setCorePoolSize(8);
        //最大线程数
        executor.setMaxPoolSize(16);
        //队列容量
        executor.setQueueCapacity(100);
        //活跃时间60秒
        executor.setKeepAliveSeconds(600);
        //线程名字前缀
        executor.setThreadNamePrefix("====我的异步任务执行者-");
        //初始化
        executor.initialize();
        //关闭时阻止60秒，让容器其他程序完成他们的任务
        executor.setAwaitTerminationSeconds(60);
        //等所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }

}
